package com.bs.regsystemapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.regsystemapi.dao.PatRegRecordDao;
import com.bs.regsystemapi.entity.PatPayRecord;
import com.bs.regsystemapi.entity.PatPerson;
import com.bs.regsystemapi.entity.PatRegRecord;
import com.bs.regsystemapi.entity.UserEntity;
import com.bs.regsystemapi.modal.dto.doctor.QueryDoctorsForm;
import com.bs.regsystemapi.modal.dto.patregrecord.*;
import com.bs.regsystemapi.modal.dto.surplus.AddSurplus;
import com.bs.regsystemapi.modal.vo.doctor.DoctorInfo;
import com.bs.regsystemapi.modal.vo.patpayrecord.RegInfo;
import com.bs.regsystemapi.service.*;
import com.bs.regsystemapi.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author ning
 * @Date 2023/1/25 18:55
 */
@Service
public class PatRegRecordServiceImpl extends ServiceImpl<PatRegRecordDao, PatRegRecord> implements PatRegRecordService {

    @Autowired
    private UserService doctorService;
    @Autowired
    private PatPersonService patPersonService;
    @Autowired
    private PatPayRecordService patPayRecordService;
    @Autowired
    private ReserveSurplusService reserveSurplusService;

    @SneakyThrows
    @Override
    public List<PatRegRecord> getPatRegRecordByOther(PatRegRecordRequestForm form) {
        List<PatRegRecord> patRegRecords = new ArrayList<>();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        QueryDoctorsForm doctorForm = new QueryDoctorsForm();
        QueryWrapper<PatRegRecord> queryWrapperByPatRegRecord = new QueryWrapper<>();
        List<UserEntity> userEntityList;
        List<DoctorInfo> doctorInfoList;
        List<PatRegRecord> resultList = new ArrayList<>();

        // 1、参数：医生名字
        if (StringUtils.isNotEmpty(form.getUserRealName())) {
            queryWrapper.eq("user_real_name", form.getUserRealName());
            queryWrapper.eq("is_delete", "1");
            userEntityList = doctorService.getBaseMapper().selectList(queryWrapper);
            queryWrapper.clear();
            // 遍历医生列表
            for (UserEntity user : userEntityList) {
                queryWrapperByPatRegRecord.eq("doctor_no", user.getUserNo());
                // 结果：预约记录列表
                patRegRecords.addAll(this.baseMapper.selectList(queryWrapperByPatRegRecord));
                queryWrapperByPatRegRecord.clear();
            }
            // 5、参数：医生名字+预约日期
            if (StringUtils.isNotEmpty(form.getTime())) {
                // 遍历预约记录列表
                for (PatRegRecord record : patRegRecords) {
                    // 筛选预约日期
                    Date date = DateUtil.toDate(form.getTime(), "yyyy-MM-dd");
                    if (record.getVisitData().equals(date)) {
                        // 存入返回结果中
                        resultList.add(record);
                    }
                }
                // 4、参数：医生名字+科室
            } else if (StringUtils.isNotEmpty(form.getUserDepartment())) {
                // 遍历医生列表
                for (UserEntity info : userEntityList) {
                    // 筛选科室：判断传入科室是否与遍历科室相同
                    if (form.getUserDepartment().equals(info.getUserDepartment())) {
                        // 通过该医生编号获取预约记录
                        queryWrapperByPatRegRecord.eq("doctor_no", info.getUserNo());
                        resultList.addAll(this.baseMapper.selectList(queryWrapperByPatRegRecord));
                        queryWrapperByPatRegRecord.clear();
                    }
                }
            } else {
                resultList.addAll(patRegRecords);
            }
            return resultList;
        }

        // 2、参数：二级科室ID
        if (StringUtils.isNotEmpty(form.getUserDepartment())) {
            doctorForm.setUserDepartment(form.getUserDepartment());
            // 参数：二级科室ID 结果：医生列表
            doctorInfoList = doctorService.getDoctorsInfo(doctorForm);
            // 遍历医生列表
            for (DoctorInfo info : doctorInfoList) {
                queryWrapperByPatRegRecord.eq("doctor_no", info.getUserNo());
                List<PatRegRecord> patRegRecordList = this.baseMapper.selectList(queryWrapperByPatRegRecord);
                queryWrapperByPatRegRecord.clear();
                // 6、参数：预约日期+二级科室ID
                if (StringUtils.isNotEmpty(form.getTime())) {
                    // 预约记录列表中筛选预约日期
                    for (PatRegRecord patRegRecord : patRegRecordList) {
                        Date date = DateUtil.toDate(form.getTime(), "yyyy-MM-dd");
                        if (patRegRecord.getVisitData().equals(date)) {
                            resultList.add(patRegRecord);
                        }
                    }
                } else {
                    // 参数只传入二级科室ID
                    resultList.addAll(patRegRecordList);
                }
            }
            return resultList;
        }

        // 3、参数：预约日期
        if (StringUtils.isNotEmpty(form.getTime())) {
            queryWrapperByPatRegRecord.eq("visit_data", form.getTime());
            resultList.addAll(this.baseMapper.selectList(queryWrapperByPatRegRecord));
            return resultList;
        }

        return resultList;
    }

    @Override
    public List<PatRegRecordDetailInfo> getPatRegRecordByRegStateAndPatNo(String regState, String patNo) {
        List<PatRegRecordDetailInfo> resultList = new ArrayList<>();
        List<PatRegRecord> patRegRecordList;
        PatPerson patPerson;

        // 条件查询就诊卡号，字段pat_no，并且is_delete为1（记录未被删除）
        patPerson = patPersonService.getOne(
                new QueryWrapper<PatPerson>()
                        .eq("pat_no", patNo)
                        .eq("is_delete", 1)
        );
        QueryWrapper<PatRegRecord> queryWrapper = new QueryWrapper<PatRegRecord>()
                .eq("person_no", patPerson.getPersonNo());
        if (StringUtils.isNotEmpty(regState)) {
            queryWrapper.eq("reg_state", regState);
        }
        // 就诊卡号查询挂号记录
        patRegRecordList = this.baseMapper.selectList(queryWrapper);

        PatRegRecordDetailInfo info;
        for (PatRegRecord patRegRecord : patRegRecordList) {
            info = new PatRegRecordDetailInfo();
            DoctorInfo doctorInfo = doctorService.getDoctorInfo(patRegRecord.getDoctorNo());
            // 医生科室
            info.setUserDepartment(doctorInfo.getSecondDepartment());
            // 医生姓名
            info.setUserRealName(doctorInfo.getUserRealName());
            // 医生职称
            info.setUserPosition(doctorInfo.getUserPosition());
            // 预约价钱
            info.setReservePrice(doctorInfo.getReservePrice());
            BeanUtils.copyProperties(patRegRecord, info);
            // 就诊人姓名
            info.setPatName(patPerson.getPersonName());
            resultList.add(info);
        }

        return resultList;
    }

    @Override
    public Map<String, Object> getPatRegRecordDetail(String regNo) {
        Map<String, Object> result = new HashMap<>(10);
        QueryWrapper<PatRegRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reg_no", regNo);
        // 预约记录
        PatRegRecord patRegRecord = this.baseMapper.selectOne(queryWrapper);
        // 医生信息
        DoctorInfo doctorInfo = doctorService.getDoctorInfo(patRegRecord.getDoctorNo());

        // 医生服务费
        PatPayRecord patPayRecord = patPayRecordService.getBaseMapper().selectOne(
                new QueryWrapper<PatPayRecord>()
                        .eq("reg_no", regNo)
        );
        // 就诊人信息
        PatPerson patPerson = patPersonService.getBaseMapper().selectOne(
                new QueryWrapper<PatPerson>()
                        .eq("person_no", patRegRecord.getPersonNo())
        );

        result.put("patRegRecord", patRegRecord);
        result.put("doctorInfo", doctorInfo);
        result.put("patPayRecord", patPayRecord);
        result.put("patPerson", patPerson);

        return result;
    }

    @Override
    public List<PatRegRecordDetailInfo> getPatRegRecordByRegNo(String patNo) {
        List<PatRegRecordDetailInfo> resultList = new ArrayList<>();
        // 条件查询就诊卡号，字段pat_no，并且is_delete为1（记录未被删除）
        PatPerson patPerson = patPersonService.getOne(
                new QueryWrapper<PatPerson>()
                        .eq("pat_no", patNo)
                        .eq("is_delete", 1)
        );
        // 就诊卡号查询挂号记录
        List<PatRegRecord> patRegRecordList = this.baseMapper.selectList(
                new QueryWrapper<PatRegRecord>()
                        .eq("person_no", patPerson.getPersonNo())
        );

        PatRegRecordDetailInfo info;
        for (PatRegRecord patRegRecord : patRegRecordList) {
            info = new PatRegRecordDetailInfo();
            DoctorInfo doctorInfo = doctorService.getDoctorInfo(patRegRecord.getDoctorNo());
            // 挂号记录内的预约号查询付费表记录
            PatPayRecord patPayRecord = patPayRecordService.getOne(
                    new QueryWrapper<PatPayRecord>()
                            .eq("reg_no", patRegRecord.getRegNo())
            );
            // 订单状态
            info.setOrderState(patPayRecord.getOrderState());
            // 医生科室
            info.setUserDepartment(doctorInfo.getSecondDepartment());
            // 医生姓名
            info.setUserRealName(doctorInfo.getUserRealName());
            // 医生职称
            info.setUserPosition(doctorInfo.getUserPosition());
            // 预约价钱
            info.setReservePrice(doctorInfo.getReservePrice());
            BeanUtils.copyProperties(patRegRecord, info);
            // 就诊人姓名
            info.setPatName(patPerson.getPersonName());
            resultList.add(info);
        }
        return resultList;
    }

    @Override
    public String savePatRegRecord(AddPatRegRecordForm form) {
        PatRegRecord patRegRecord = new PatRegRecord();

        // 生成预约号(4位随机数+10位时间戳)
        String time = Long.toString(System.currentTimeMillis());
        time = time.substring(0, time.length() - 3);
        String regNo = RandomUtils.getrandom(4) + time;
        // 预约号
        patRegRecord.setRegNo(regNo);
        // 是否删除
        patRegRecord.setIsDelete("1");
        // 创建时间
        patRegRecord.setCreatTime(new Date());
        // 预约状态: 0失败 1成功
        patRegRecord.setIsSuccess("1");
        // 去空格
        form.setVisitTime(form.getVisitTime().trim());
        BeanCopyUtils.copyProperties(form, patRegRecord);
        // 新增挂号记录
        this.baseMapper.insert(patRegRecord);

        // 构造参数，更新医生下预约总数量
        AddSurplus addSurplus = new AddSurplus();
        addSurplus.setDoctorNo(patRegRecord.getDoctorNo());
        addSurplus.setDate(patRegRecord.getVisitData());
        addSurplus.setTime(patRegRecord.getVisitTime());
        // 更新医生被预约数量
        reserveSurplusService.addSurplus(addSurplus);

        return patRegRecord.getRegNo();
    }

    @Override
    public ManagePageResult getPatRegRecordByDoctorNo(PatRegRecordListForm form) {
        PageHelper.startPage(form.getPageNum(), form.getPageSize());
        List<PatRegRecord> patRegRecordList = this.baseMapper.getPatRegRecordByDoctorNo(form);
        PageInfo<PatRegRecord> patRegRecordPageInfo = new PageInfo<>(patRegRecordList);
        return ManagePageResult.getPageResult(patRegRecordPageInfo);
    }

    @Override
    public ManagePageResult getRegInfo(QueryRegInfoForm form) {
        PageHelper.startPage(form.getPageNum(), form.getPageSize());
        List<RegInfo> regInfo = this.baseMapper.getRegInfo(form);
        PageInfo<RegInfo> regInfoPageInfo = new PageInfo<>(regInfo);
        return ManagePageResult.getPageResult(regInfoPageInfo);
    }

    @Override
    public ManagePageResult getHisRegInfo(QueryRegInfoForm form) {
        PageHelper.startPage(form.getPageNum(), form.getPageSize());
        List<RegInfo> regInfo = this.baseMapper.getHisRegInfo(form);
        PageInfo<RegInfo> regInfoPageInfo = new PageInfo<>(regInfo);
        return ManagePageResult.getPageResult(regInfoPageInfo);
    }


}
